<template>
    <div class="containers container">
        <div class="container top-return">
            <div class="inline-block">
                <el-page-header @back="goBack" :content="currentItem.title"></el-page-header>
            </div>
        </div>
        <div class="container spc">
            <el-form ref="formRef" :model="currentItem.rowData" :rules="rules" label-width="150px" class="demo-ruleForm">
                <!-- 商品信息 -->
                <div class="title head-title bottom-border">账户信息</div>
                <el-row class="el-rows">
                    <el-col :span="12">
                        <el-form-item label="对比库名称:" prop="compareName" style="margin-bottom: 0;">
                            <el-input v-model="currentItem.rowData!.compareName" placeholder="请输入对比库名称"
                                :disabled="currentItem.title == '编辑'" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <div class="title head-title bottom-border">产品明细</div>
                <!-- 新增搜索栏 -->
                <el-row class="search-container" style="margin-bottom: 16px;">
                    <el-col :span="6">
                        <el-form-item label="产品名称">
                            <el-input v-model="searchForm.productName" placeholder="请输入产品名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="系列">
                            <!-- <el-select v-model="searchForm.category" placeholder="请选择系列">
                                <el-option 
                                    v-for="category in mockCategories" 
                                    :key="category"
                                    :label="category"
                                    :value="category"
                                />
                            </el-select> -->
                            <MySelect v-model="searchForm.category" :request-api="listWithFather"
                                :fieldNames="{ label: 'childName', value: 'childName', labelName: '', autoLable: false }"
                                :data="currentItem" :initParam="{ pageNum: 1, pageSize: 99999, fatherName: '产品系列' }" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </el-col>
                </el-row>

                <!-- 可选/已选系列组件 -->
                <el-row class="series-container">
                    <el-col :span="10">
                        <el-card title="可选" class="series-card">
                            <span style="font-weight: bold;">可选</span>
                            <el-scrollbar ref="scrollBar" height="320px"> <!-- 添加ref标记滚动容器 -->
                                <!-- 修改后的循环项 -->
                                <div v-for="(series, index) in filteredSelectedSeries" class="series-item"
                                    @click.stop="handleSelect(series, index)">
                                    <!-- 产品图片（添加懒加载和占位符） -->
                                    <el-image :src="series.productUrl" class="series-thumb"
                                        :preview-src-list="[series.productUrl]" fit="cover" preview-teleported @click.stop
                                        lazy 
                                        :scroll-container="scrollBar" 
                                        :placeholder="placeholderSvg" 
                                        />
                                        <!-- 产品信息 -->
                                        <div class="series-info">
                                            <span class="series-code">代码：{{ series.productCode }}</span>
                                            <span class="series-name">产品名称:{{ series.productName }}</span>
                                            <span class="series-meta">系列：{{ series.childName }}</span>
                                            <span class="series-meta">材质：{{ series.material }}</span>
                                        </div>
                                </div>
                            </el-scrollbar>
                        </el-card>
                    </el-col>

                    <el-col :span="10">
                        <el-card title="已选" class="series-card">
                            <span style="font-weight: bold;">已选</span>
                            <el-scrollbar ref="scrollBar" height="320px"> <!-- 添加ref标记滚动容器 -->
                                <!-- 修改为遍历过滤后的数据 -->
                                <div v-for="(series, index) in selectedSeries" class="series-item"
                                    @click.stop="handleRemove(series, index)">
                                    <!-- 产品图片（添加懒加载和占位符） -->
                                    <el-image :src="series.productUrl" class="series-thumb"
                                        :preview-src-list="[series.productUrl]" fit="cover" preview-teleported @click.stop
                                        lazy 
                                        :scroll-container="scrollBar" 
                                        :placeholder="placeholderSvg" 
                                        />
                                        <!-- 产品信息 -->
                                        <div class="series-info">
                                            <span class="series-code">代码：{{ series.productCode }}</span>
                                            <span class="series-name">产品名称: {{ series.productName }}</span>
                                            <span class="series-meta">系列：{{ series.childName }}</span>
                                            <span class="series-meta">材质：{{ series.material }}</span>
                                        </div>
                                        <!-- 保留删除图标 -->
                                        <el-icon class="remove-icon">
                                            <Delete />
                                        </el-icon>
                                </div>
                            </el-scrollbar>
                        </el-card>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="bot-pos-submit">
            <el-button class="simple-btn" @click="goBack">关闭</el-button>
            <el-button class="standard-btn" v-if="currentType != '查看'" @click="submitForm">提交</el-button>
        </div>

        <MyDiolg ref="dialogRef" />
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, toRefs, defineProps, onMounted, nextTick, watch } from "vue";
import {
    CirclePlus,
    Delete,
    EditPen,
    Download,
    Upload,
    View,
    Refresh,
} from "@element-plus/icons-vue";
import {
    listDealerManage,
} from "@/api/system/dealerManage";
import {
    listProduct
} from "@/api/zc/productLibrary";
import {
    listWithFather
} from "@/api/zc/classification";
// import MyDiolg from "./Form.vue";
import { ElMessage } from "element-plus";
let memberFiled = { label: "dealerName", value: "id", labelName: "dealerName", autoLable: false };
const activeName = ref('first')
const dialogRef = ref(null);
const handleClick = (tab: any, event: Event) => {
    console.log(tab, event)
}
const formRef = ref();
const emit = defineEmits(["changeItem"]);
interface Props {
    currentItem: any;
    currentType: string;
}

// 添加滚动容器ref
const scrollBar = ref(null);

// 添加占位符SVG（浅灰色背景）
const placeholderSvg = ref(`
    <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
        <rect width="100%" height="100%" fill="#f5f7fa"/>
    </svg>
`);


const goBack = () => {
    emit("changeItem", "0");
};

// 接受父组件参数，配置默认值
const props = withDefaults(defineProps<Props>(), {
    currentItem: {
        rowData: {},
        api: null,
    },
    currentType: "",
});
//提交
const submitForm = async () => {
    formRef.value!.validate(async (valid) => {
        if (!valid) return;
        try {
            // if (selectedSeries.value.length == 0) {
            //     ElMessage.error({ message: '请选择销售系列！' });
            //     return;
            // } else {
            //     props.currentItem.rowData.optionalSeries = selectedSeries.value.map(item => item.name).join(",");
            // }

            const categories = selectedSeries.value.map(item => item.category);
            const uniqueCategories = new Set(categories.filter(Boolean));
            await props.currentItem.api({
                ...props.currentItem.rowData, detailList: selectedSeries.value.map(item => {
                    return {
                        ...item,
                        // productId: item.id,
                    }
                }), productNums: selectedSeries.value.length, childNums: uniqueCategories.size
            });
            ElMessage.success({ message: `${props.currentType}成功！` });
            goBack();
        } catch (error) {
            console.log(error);
        }
    });
};
const dialogCallBack = (data: any, index: number | null) => {
    console.log("回调", data);
    console.log("index", index);
    // 修改点：判断 index 是否为非 null（包括 0 等数字情况）
    if (index !== null) {
        props.currentItem.rowData.zcSupplierCertList[index] = data;
    } else {
        props.currentItem.rowData.zcSupplierCertList.push(data);
    }
};
const openDiolg = (title: string, row: any, index: number | null) => {
    const params = {
        title,
        isView: title === "查看",
        rowData: { ...row },
        api: title === "新增" ? dialogCallBack : title === "修改" ? dialogCallBack : undefined,
        index: index
        // getTableList: proTable.value?.getTableList,
    };
    dialogRef.value?.acceptParams(params);
};
// 表单验证规则（修改）
const rules = reactive({
    account: [  // 登录账号验证
        { required: true, message: '请输入登录账号', trigger: ['blur', 'change'] },
        { min: 3, max: 20, message: '账号长度在3-20个字符之间', trigger: ['blur', 'change'] }
    ],
    password: [  // 登录密码验证
        { required: true, message: '请输入登录密码', trigger: ['blur', 'change'] },
        { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: ['blur', 'change'] }
    ],
    carrierName: [  // 经销商名称验证
        { required: true, message: '请输入经销商名称', trigger: ['blur', 'change'] }
    ],
    director: [  // 负责人验证
        { required: true, message: '请输入负责人', trigger: ['blur', 'change'] }
    ],
    phone: [  // 电话验证（手机号格式）
        { required: true, message: '请输入联系电话', trigger: ['blur', 'change'] },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的11位手机号', trigger: ['blur', 'change'] }
    ],
    compareName: [  // 门店地址验证
        { required: true, message: '对比库名称不能为空', trigger: ['blur', 'change'] }
    ],
    belong: [  // 所属机构验证
        { required: true, message: '请选择所属机构', trigger: ['blur', 'change'] }
    ],
    status: [  // 状态验证
        { required: true, message: '请选择状态', trigger: ['change'] }
    ]
});
const availableSeries = ref([]);
const selectedSeries = ref([]);
// 初始化系列数据（使用模拟数据）
const initSeriesData = async () => {
    // 模拟可选系列数据（可根据需要调整）
    // const mockAvailableSeries = [
    //     { name: '奢华印象', id: 1 },
    //     { name: '经典系列', id: 2 },
    //     { name: '现代简约', id: 3 },
    //     { name: '轻奢风尚', id: 4 },
    //     { name: '普通质感', id: 5 },
    // ];
    // let { data } = await listWithFather({ fatherName: "产品系列" })
    let { rows } = await listProduct({ pageNum: 1, pageSize: 99999 })
    if (props.currentType === '新增') {
        // props.currentItem.rowData.availableSeries = data.map((item: any) => { return { name: item.childName, id: item.id } });
        // availableSeries.value = data.map((item: any) => { return { name: item.childName, id: item.id } });
        availableSeries.value = rows.map(item => { return { ...item, productId: JSON.parse(JSON.stringify(item.id)), id: "" } });
    } else {
        // // 编辑状态：
        // 1. 将已选系列转换为带id的对象数组（假设原已选存储的是名称，需匹配id）
        // const selectedWithId = props.currentItem.rowData.selectedSeries.map((item: any, index: number) => {
        //     let obj = rows.find((item2: any) => item2.id === item.id);
        //     return { ...obj}
        // });
        const selectedWithId = props.currentItem.rowData.selectedSeries

        // 2. 从可选系列中过滤掉已选
        // const availableFiltered = rows.filter((item: any) => !selectedWithId.filter((selected: any) => selected.id != item.id));
        let availableFiltered = rows.filter((item: any) => {
            return !selectedWithId.some(selected => selected.productId === item.id);
        });
        availableFiltered = availableFiltered.map((item: any) => { return { ...item, productId: JSON.parse(JSON.stringify(item.id)), id: "" } });
        console.log("selectedWithId", selectedWithId)
        console.log("availableFiltered", availableFiltered)

        const arr = availableFiltered;

        // 分批添加逻辑（每批添加5个，可根据需求调整）
        const batchSize = 5; // 每批数量
        availableSeries.value = []; // 清空原数据

        // 分批处理
        for (let i = 0; i < arr.length; i += batchSize) {
            const batch = arr.slice(i, i + batchSize);
            availableSeries.value.push(...batch); // 批量添加当前批次
            await nextTick(); // 等待DOM更新
        }
        console.log("availableFiltered", availableSeries.value)
        // props.currentItem.rowData.selectedSeries = [...selectedWithId];
        selectedSeries.value = [...selectedWithId];

    }
    filterSelectedSeries();
};

// 处理选中系列
const handleSelect = (series, index) => {
    const newAvailable = [...filteredSelectedSeries.value];
    const newSelected = [...selectedSeries.value];

    // 从可选移动到已选
    const [movedItem] = newAvailable.splice(index, 1);
    newSelected.push(movedItem);
    //把availableSeries.value 对应的movedItem也移除掉
    const newAvailableSeries = availableSeries.value.filter((item: any) => item.productId != movedItem.productId);
    availableSeries.value = newAvailableSeries;
    // 使用 Vue.set 确保响应性
    filteredSelectedSeries.value = newAvailable;
    selectedSeries.value = newSelected;
};

// 处理移除系列
// const handleRemove = (series, index) => {
//     const newAvailable = [...availableSeries.value];
//     const newSelected = [...selectedSeries.value];

//     // 从已选移动到可选
//     const [movedItem] = newSelected.splice(index, 1);
//     newAvailable.push(movedItem);

//     // 使用 Vue.set 确保响应性
//     // availableSeries.value = newAvailable;
//     availableSeries.value.push(series);
//     selectedSeries.value = newSelected;
//     console.log("availableSeries", availableSeries.value)
// };

const handleRemove = (series, index) => {
    // 1. 复制当前已选和可选数组（创建新引用）
    const newSelected = selectedSeries.value.filter((_, i) => i !== index); // 移除目标项
    const newAvailable = [...availableSeries.value, series]; // 将移除项添加到可选数组

    filteredSelectedSeries.value =  [...filteredSelectedSeries.value, series];
    // 2. 替换为新数组（强制触发响应式更新）
    availableSeries.value = newAvailable; // 关键：替换可选数组引用
    selectedSeries.value = newSelected;   // 替换已选数组引用
};

// 新增搜索相关变量
const searchForm = ref({
    productName: '',  // 产品名称输入框
    category: ''      // 系列下拉框
});

// 模拟系列数据（可根据实际需求调整）
const mockCategories = ref(['经典系列', '现代简约', '轻奢风尚', '普通质感']);

// 过滤后的已选系列（用于显示）
const filteredSelectedSeries = ref([]);

// 过滤函数
const filterSelectedSeries = () => {
    filteredSelectedSeries.value = availableSeries.value.filter(series => {
        // 产品名称模糊匹配（包含输入内容）
        const nameMatch = series.productName.includes(searchForm.value.productName);
        // 系列精确匹配（如果有选择）
        const categoryMatch = !searchForm.value.category || series.childName === searchForm.value.category;
        return nameMatch && categoryMatch;
    });
};

// 查询操作
const handleSearch = () => {
    filterSelectedSeries();
};

// 重置操作
const handleReset = () => {
    searchForm.value.productName = '';
    searchForm.value.category = '';
    console.log("selectedSeries", selectedSeries)
    filteredSelectedSeries.value = [...availableSeries.value];  // 恢复原始数据
};

// 初始化时同步过滤数据
watch(selectedSeries, () => {
    filterSelectedSeries();
}, { immediate: true });

onMounted(() => {
    // if (props.currentType === '编辑') {
    //     initSeriesData();
    // }
    initSeriesData();
});
</script>
<style lang="scss" scoped>
.search-container {
    padding: 0 16px; // 与卡片内边距一致

    .el-form-item {
        margin-bottom: 0; // 消除默认下边距
    }

    .el-input,
    .el-select {
        width: 200px; // 统一输入框宽度
    }

    .el-button {
        margin-left: 12px; // 按钮间距
    }
}

.bot-pos-submit {
    position: fixed;
    height: 60px;
    background: white;
    width: calc(100vw - 252px);
    bottom: 0px;
    text-align: center;
    line-height: 60px;
    z-index: 999;
}

/* 卡片容器样式 */
// .el-rows {
//     display: flex;
//     flex-wrap: wrap;
//     margin: -10px;
// }

// .el-col {
//     padding: 10px;
// }

/* 卡片样式 */
.my-card {
    display: flex;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 15px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    height: 100%;
}

.my-card:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    transform: translateY(-3px);

}

.left-img {
    flex-shrink: 0;
    margin-right: 15px;
}

.left-img img {
    width: 60px;
    height: 60px;
    border-radius: 4px;
    object-fit: cover;
}

.right-info {
    flex-grow: 1;
}

.right-info-title {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 8px;
}

.right-info-title-left {
    display: flex;
    flex-direction: column;
}

.right-info-title-left span:first-child {
    font-weight: 600;
    font-size: 14px;
    color: #303133;
    margin-bottom: 4px;
}

.right-info-title-left span:last-child {
    font-size: 12px;
    color: #909399;
}

.card-actions {
    display: flex;
    align-items: center;
}

.card-actions .el-button {
    padding: 4px;
    margin-left: 5px;
    font-size: 16px;
}

.series-container {
    padding: 20px 16px; // 增加左右内边距
    gap: 32px; // 增大两栏间距
    justify-content: center; // 内容居中
}

.series-card {
    // height: 320px; // 稍微增加高度
    border: 1px solid #f0f2f5; // 浅边框
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); // 轻微阴影

    .el-card__header {
        padding: 12px 16px; // 调整标题内边距
        background: #f8f9fa; // 标题背景色
        border-bottom: 1px solid #f0f2f5; // 标题底边框
    }

    .el-card__title {
        font-size: 14px;
        color: #303133;
        font-weight: 600; // 标题加粗
    }

    .el-card__body {
        padding: 8px 0; // 内容区上下内边距
        height: 260px; // 内容区高度
    }
}

.series-item {
    // 调整为flex布局，包含删除图标
    display: flex;
    align-items: center;
    justify-content: space-between; // 新增：使信息和删除图标分居两侧
    padding: 12px 16px;
    margin: 4px 8px;
    border-radius: 6px;
    font-size: 14px;
    color: #606266;
    transition: all 0.2s;
    cursor: pointer;

    &:hover {
        background: #f5f7fa;
        transform: translateX(4px);
    }

    // 产品缩略图样式
    .series-thumb {
        width: 50px;
        height: 50px;
        border-radius: 4px;
        flex-shrink: 0; // 防止图片被压缩
        margin-right: 12px;
    }

    // 产品信息区域（左侧）
    .series-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 2px; // 信息项间距

        .series-code {
            font-size: 12px;
            color: #909399;
        }

        .series-name {
            font-weight: 600;
            color: #303133;
            // 文字溢出处理
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .series-meta {
            font-size: 12px;
            color: #606266;
        }
    }

    // 删除图标样式
    .remove-icon {
        flex-shrink: 0; // 防止图标被压缩
        color: #f56c6c; // 红色删除图标
        cursor: pointer;
        transition: color 0.2s;

        &:hover {
            color: #f03a3a; // 悬停加深红色
        }
    }
}
</style>

